package spring.cloud.tasks.api.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import spring.cloud.tasks.api.database.entity.ZooKeeperClusterDto;
import spring.cloud.tasks.api.database.service.NameSpaceZooKeeperClusterMappingDtoService;
import spring.cloud.tasks.api.database.service.ZooKeeperClusterDtoService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/rest/v1/discovery")
public class DiscoveryController {


    @Resource
    private ZooKeeperClusterDtoService zooKeeperClusterInfoService;

    @Resource
    private NameSpaceZooKeeperClusterMappingDtoService nameSpaceZooKeeperClusterMapping4SqlService;

    /**
     * 发现namespace相关注册信息.
     */
    //@Audit(type = AuditType.REST)
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity discover(String namespace) throws RuntimeException {
        Map<String, String> response = new HashMap<>(2);
        response.put("connectString", getConnectString(namespace));
        return ResponseEntity.ok(response);
    }

    /**
     * 返回ZK连接串
     */
    private String getConnectString(String nameSpace) throws RuntimeException {
        if (StringUtils.isBlank(nameSpace)) {
            throw new RuntimeException(String.format("namespace"));
        }
        String zooKeeperClusterKey = nameSpaceZooKeeperClusterMapping4SqlService.getZooKeeperClusterKey(nameSpace);
        if (zooKeeperClusterKey == null) {
            throw new RuntimeException("The namespace：[" + nameSpace + "] is not registered in Saturn.");
        }
        ZooKeeperClusterDto zooKeeperClusterInfo = zooKeeperClusterInfoService.getZooKeeperClusterInfoByZooKeeperClusterKey(zooKeeperClusterKey);
        if (zooKeeperClusterInfo == null) {
            throw new RuntimeException("The clusterKey: [" + zooKeeperClusterKey + "] is not configured in db for " + nameSpace);
        }
        return zooKeeperClusterInfo.getConnectString();
    }


}
